﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using DevelopTool.Bll.LocalDbBlls;
using DevelopTool.Bll.NoteBlls;
using System.Windows.Forms;
using DevelopTool.Common;
using DevelopTool.Forms.CommonForms;
using DevelopTool.Forms.LodingForm;
using DevelopTool.Model.AssemblyyModels;
using DevelopTool.Model.CodeModels;
using DevelopTool.Model.DbModels.TableRelation;
using DevelopTool.Model.DbModels;
using DevelopTool.Model.LuckDrawModels;
using DevelopTool.Model.NoteModels;
using DevelopTool.Model.OffLineModels;
using DevelopTool.Model.RemoteModels;
using DevelopTool.Model.SchedulerModels;
using DevelopTool.Model.TipsModels;
using DevelopTool.Model;
using Sunny.UI;

namespace DevelopTool.Forms.CommonHelpers
{
    public class ExportHelper : BaseHelper
    {
        /// <summary>
        /// DataTable导出为Json
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="exporName"></param>
        public static void ExportDataToJSON(DataTable dataTable, string exporName)
        {
            if (dataTable == null || dataTable.Rows.Count <= 0) return;

            IgnoringColumns(dataTable);

            string filter = "Json文件|*.json";
            string fileName = exporName + "_" + DateTime.Now.DateTimeString(false) + ".json";

            if (!Dialogs.SaveFileDialog(ref fileName, filter)) return;
            if (string.IsNullOrEmpty(fileName)) return;

            LoadingHelper.ShowLoading($"正在导出{exporName}JSON...", () =>
            {
                File.WriteAllText(fileName, dataTable.DataTableToJson(), Encoding.UTF8);
            });
            UINotifierHelper.ShowNotifier($"已导出【{exporName}】Json", UINotifierType.INFO, UIStyles.CurrentResources.InfoTitle, false, 2000);
        }


        /// <summary>
        /// DataTable导出为Excel
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="exporName"></param>
        public static void ExportDataToExcel(DataTable dataTable, string exporName)
        {
            if (dataTable == null || dataTable.Rows.Count <= 0) return;

            IgnoringColumns(dataTable);

            string filter = "Excel文档|*.xls|Excel|*.xlsx";
            string fileName = exporName + "_" + DateTime.Now.DateTimeString(false);

            if (!Dialogs.SaveFileDialog(ref fileName, filter)) return;
            if (string.IsNullOrEmpty(fileName)) return;

            LoadingHelper.ShowLoading($"正在导出{exporName}Excel...", () =>
            {
                ExcelHelper.ExportToExcel(dataTable, fileName);
            });

            UINotifierHelper.ShowNotifier($"已导出【{exporName}】Excel", UINotifierType.INFO, UIStyles.CurrentResources.InfoTitle, false, 2000);
        }


        /// <summary>
        /// 导出本地数据库
        /// </summary>
        public static void ExportLocalDB()
        {
            List<TreeNode> treeNodes = new List<TreeNode>() {
                    new TreeNode{ Text = "笔记", Tag = typeof(Note).Name},
                    new TreeNode{ Text = "笔记附件", Tag = typeof(NoteFile).Name},
                    new TreeNode{ Text = "代码", Tag = typeof(Code).Name},
                    new TreeNode{ Text = "数据库连接", Tag = typeof(DbInfo).Name},
                    new TreeNode{ Text = "数据库资源分组", Tag = typeof(DbSourceGroup).Name},
                    new TreeNode{ Text = "数据库表关系", Tag = typeof(TableRelation).Name},
                    new TreeNode{ Text = "离线数据", Tag = typeof(OffLine).Name},
                    new TreeNode{ Text = "程序集缓存", Tag = typeof(Assemblyy).Name},
                    new TreeNode{ Text = "选择困难症", Tag = typeof(LuckDraw).Name},
                    new TreeNode{ Text = "远程连接", Tag = typeof(Remote).Name},
                    new TreeNode{ Text = "定时任务", Tag = typeof(Scheduler).Name},
                    new TreeNode{ Text = "事项提醒", Tag = typeof(Tips).Name},
            };

            using (ComboBoxForm comboBoxForm = new ComboBoxForm("请选择需要导出的数据模块功能", treeNodes, mustBeSelected: true))
            {
                if (comboBoxForm.ShowDialog() != DialogResult.OK) return;

                using (SaveFileDialog sfd = new SaveFileDialog())
                {
                    FileInfo fileInfo = new FileInfo(LocalUser.DbFilePath);
                    sfd.Title = $"{GlobalData.AppName_zh}数据库导出({fileInfo.Name})路径选择";
                    sfd.Filter = $"*{GlobalData.AppDbFileExtension}|*{GlobalData.AppDbFileExtension}";
                    sfd.FileName = fileInfo.Name;
                    if (sfd.ShowDialog() != DialogResult.OK) return;

                    LoadingHelper.ShowLoading("正在导出数据库", () =>
                    {
                        string tempDbPath = GlobalData.AppTempDirectory + fileInfo.Name;//数据库临时路径

                        //先复制到临时目录
                        fileInfo.CopyTo(tempDbPath, true);

                        //删除未选择的数据模块
                        foreach (TreeNode treeNode in treeNodes)
                        {
                            if (!comboBoxForm.SelectedNodes.Exists(it => it.Tag.ToString() == treeNode.Tag.ToString()))
                            {
                                //若未选择笔记附件，则删除笔记附件
                                if (treeNode.Tag.ToString() == typeof(NoteFile).Name) new NoteFileBll().DeleteAllFiles(tempDbPath, LocalUser.Password);

                                LiteDbContext.DeleteTable(treeNode.Tag.ToString(), tempDbPath, LocalUser.Password);
                            }
                        }

                        LiteDbContext.ClearCache(tempDbPath, LocalUser.Password);//重新整理数据库未使用的空间                        

                        //将数据库从临时目录移动到选择的目录
                        File.Move(tempDbPath, sfd.FileName);
                    });

                    UINotifierHelper.ShowNotifier($"数据库已导出到【{sfd.FileName}】", UINotifierType.INFO, UIStyles.CurrentResources.InfoTitle, false, 2000);
                }
            }
        }
    }
}
